import { actionDebounce, showActionSheet, toPage, toTargetMiniProgramDetailPage } from '@/utils/mpHelper'
import { toTargetMiniProgramTypes } from '@/constants/AppInfo'
import {
  checkLocationPermission,
  OS_SYSTEM_LOCATION_PERMISSION,
  APPLICATION_LOCATION_PERMISSION,
  WXMP_LOCATION_PERMISSION,
} from '@/utils/basicHelper'
import type { ApplianceData } from '@/types/appliance'
import { encryptUserPhone } from '@/api/account'
import { useApplianceStore } from '@/store/appliance'
import { useI18n } from 'vue-i18n'
import { useWebsocketListener } from '@/utils/socket/WebSocketHandlerImp'
import { WebsocketManager } from '@/utils/socket/WebsocketManager'
import type { WS } from '@/utils/socket/types'
import { handleStatus } from '@/handle/appliance'
import { OPERATION_KEY } from '@/constants/Command'

export function useApplianceMethods() {
  const i18n = useI18n()
  const applianceStore = useApplianceStore()

  // 添加家电
  const addAppliance = actionDebounce({
    showLoading: true,
    delay: 2000,
    call: async () => {
      await checkLocationPermission()
      const url = '/pages/pairing/chooseMode/index'
      await toPage(url)
    },
    catch: (error: any) => {
      if (!error.Location) return
      let title = ''
      if (error.Location === OS_SYSTEM_LOCATION_PERMISSION) {
        title = i18n.t('APP.Pairing.Error.SystemLocation.Text')
      } else if (error.Location === APPLICATION_LOCATION_PERMISSION) {
        title = i18n.t('APP.Pairing.Error.ApplicationLocation.Text')
      } else if (error.Location === WXMP_LOCATION_PERMISSION) {
        title = i18n.t('APP.Pairing.Error.WXMPLocation.Text')
      }
      showActionSheet({
        title,
        itemList: [i18n.t('Navigator.Loading.Acknowledge.Text')],
      })
    },
  })

  // 点击家电卡片
  const chooseHA = actionDebounce({
    delay: 300,
    showLoading: false,
    call: async (appliance: ApplianceData) => {
      applianceStore.setCurrent(appliance)
      await jumpToApplianceDetailPage(appliance)
    },
  })

  // 跳转到家电详情页面
  function jumpToApplianceDetailPage(appliance: ApplianceData) {
    let useAppliancePageType = appliance.type
    // 特殊处理品类
    if (['Freezer', 'Refrigerator'].includes(appliance.type)) {
      useAppliancePageType = 'FridgeFreezer'
    }

    return toPage(`/pages/appliance/${useAppliancePageType}/${useAppliancePageType}`, {
      haId: appliance.haId,
      vib: appliance.vib,
      type: appliance.type,
      brand: appliance.brand,
    })
  }

  return {
    addAppliance,
    chooseHA,
  }
}
/**
 * 去其他小程序判断
 * @param appliance
 * @returns
 */
export async function toOtherMPCheckUp(appliance: ApplianceData) {
  uni.showLoading({
    mask: true,
  })
  const isOtherMPTypes = toTargetMiniProgramTypes.includes(appliance.type)
  // 跳转到其他小程序
  if (isOtherMPTypes) {
    // 获取加密小程序用户手机号信息
    const res = await encryptUserPhone()
    const params = {
      haid: appliance.haId,
      vib: appliance.vib,
      brand: appliance.brand,
      name: appliance.name,
      sign: res.data.sign,
      phoneData: res.data.encryptDate,
      appliance_type: appliance.type,
    }
    uni.hideLoading()
    await toTargetMiniProgramDetailPage(appliance.type, params, 'Navigator.Home.Select.Appliance')
    return true
  } else {
    uni.hideLoading()
    return false
  }
}
/**
 * Websocket监听
 */
export function useApplianceListMessageListener() {
  const applianceStore = useApplianceStore()
  const applianceListMessageListener = (
    msg: WS.Message,
    options?: {
      operationTransformer: (msg: WS.MessageItem, appliance: ApplianceData) => string
    }
  ) => {
    console.info('applianceListMessageListener', msg)
    applianceStore.list.forEach(async (appliance, index) => {
      if (appliance.haId !== msg.haId) return

      // 在线离线处理
      if (msg.type === 'CONNECTED') {
        appliance.connected = true
      } else if (msg.type === 'DISCONNECTED') {
        appliance.connected = false
      }

      for (const item of (msg.items || []) as WS.MessageItem[]) {
        if (item.key === OPERATION_KEY) {
          let operationState = item.value as string
          try {
            operationState = options?.operationTransformer?.(item, appliance) || operationState
          } catch (e) {
            console.error(e)
          }
          appliance.operationState = operationState
        }
      }

      const newApplianceStatus: ApplianceData = await handleStatus(appliance)
      applianceStore.list[index] = newApplianceStatus
    })
  }
  useWebsocketListener(WebsocketManager.instance.inhouseWebsocket, (msg: WS.Message) =>
    applianceListMessageListener(msg)
  )
  useWebsocketListener(WebsocketManager.instance.oemWebsocket, (msg: WS.Message) =>
    applianceListMessageListener(msg, {
      operationTransformer: (msg: WS.MessageItem) => msg.default as string,
    })
  )
}
